//
//  MusicMeduimControl.swift
//  TimMusic
//
//  Created by nkl on 2024/10/25.
//

import SwiftUI
import WidgetKit

// 2. 提供器：定义时间线，何时刷新数据
struct MediumProvider: IntentTimelineProvider {
    typealias Intent = MusicMeduimWidgetIntent

    typealias Entry = MusicEntry

    func placeholder(in context: Context) -> MusicEntry {
        MusicEntry(date: Date(), title: "Unknown", auth: "Unknown", imageData: nil, isPlay: false, type: TimDefaultWidgetFullName, isStatic: true)
    }

    func getSnapshot(for configuration: MusicMeduimWidgetIntent, in context: Context, completion: @escaping @Sendable (MusicEntry) -> Void) {
        let entry = MusicEntry(date: Date(), title: "Unknown", auth: "Unknown", imageData: nil, isPlay: false, type: TimDefaultWidgetFullName, isStatic: false)
        completion(entry)
    }

    func getTimeline(for configuration: MusicMeduimWidgetIntent, in context: Context, completion: @escaping @Sendable (Timeline<MusicEntry>) -> Void) {
        var entries: [MusicEntry] = []

        let sharedDefaults = UserDefaults(suiteName: TimeGroupName)
        let title = sharedDefaults?.string(forKey: "widgetTitle") ?? "Default Title"
        let imageData = sharedDefaults?.data(forKey: "widgetImageData")
        let auth = sharedDefaults?.string(forKey: "widgetDetail") ?? "Default Title"
        let isPlay = sharedDefaults?.bool(forKey: "widgetPlay") ?? false
        var type: String = TimDefaultWidgetFullName
        if let id = configuration.style?.identifier, let model = TimDataManager.shared.fetchItemModel(id: id)?.itemModel {
            type = model.fullName
        }
        // 创建未来 5 小时的时间线
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: Date())!
            let entry = MusicEntry(date: entryDate, title: title, auth: auth, imageData: imageData, isPlay: isPlay, type: type, isStatic: false)
            entries.append(entry)
        }

        // 创建时间线
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

// 4. Widget 定义
struct MeidumWidget: Widget {
    let kind: String = "com.timmusic.MeidumWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: MusicMeduimWidgetIntent.self, provider: MediumProvider()) { entry in
            SimpleWidgetEntryView(entry: entry)
        }
        .contentMarginsDisabled()
        .configurationDisplayName("Medium Widget")
        .description("Choose the widget add to home screen")
        .supportedFamilies([.systemMedium]) // 支持不同大小的组件
    }
}
